import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { CacheService } from './../../services/cache.service';
import { NetService } from './../../services/net.service';
import { SocketService } from './../../services/socket.service';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {
  public userInfo: object = null;
  public breadcrumbs = [];
  constructor(
    private router: Router,
    private net: NetService,
    private cacheService: CacheService,
    private activatedRoute: ActivatedRoute,
    private socketService: SocketService
  ) {}

  get state() {
    return this.socketService.socketState;
  }
  get count() {
    return this.socketService.clientCounts;
  }

  async logout() {
    await this.net.post('/api/logout', null);
    this.socketService.close();
    this.cacheService.clearUserInfo();
    this.router.navigateByUrl('/login');
  }

  async ngOnInit() {
    this.breadcrumbs = this.getBreadcrumb(this.activatedRoute.root);
    this.router.events.forEach(event => {
      if (event instanceof NavigationEnd) {
        this.breadcrumbs = this.getBreadcrumb(this.activatedRoute.root);
      }
    });
    this.userInfo = await this.cacheService.getUserInfo();

    if (!this.socketService.socket) {
      await this.socketService.init();
    }

  }

  getBreadcrumb(bread) {
    if (bread.children.length === 0) { return bread.data.value.bread || []; }
    return this.getBreadcrumb(bread.children[0]);
  }

}




